package concordia.comp6231.rfmulticast;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;

public class RFIFOMulticast {

	private List<String> recipients = new ArrayList<String>();
	private final Semaphore semaphore1 = new Semaphore(1);
	private final Semaphore semaphore2 = new Semaphore(1);
	public static final String RFM_MSG_SENDER = "SenderName";
	public static final String RFM_MSG_DEAD_HOST = "deadName";
	
	public RFIFOMulticast() {}
	
	public RFIFOMulticast(List<String> recipients) {
		this.recipients = recipients;
	}
	
	public void listen(int port,ListernerHandler rh){
		
		System.out.println("Listenning on port: " + port + ", for class: " + rh.getClass().getName());
		try{
			semaphore2.acquire();
			ReplyHandler aReply = new ReplyHandler(port, rh); 
			aReply.start();
			semaphore2.release();
		}
		catch(InterruptedException e){
			e.printStackTrace();
		}		
	}
	
	public void send(int port, Message msg, ResultHandler sucessHandler, ResultHandler failureHandler) {
		try {
			semaphore1.acquire();
			RequestHandler aRequest = 
			new RequestHandler(port, msg, sucessHandler, failureHandler, recipients);
			//aRequest.DisplayMessage();  /* Only for me */
			aRequest.start();
			semaphore1.release();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public Message synchronosSend(int port, Message msg) {
		
		BlockingSend aBlockingSend =  new BlockingSend(port, msg, recipients);
		return aBlockingSend.sendAndWait();
	
	}
	
	protected void PrintCurrentRecipients() {

		System.out.println("Current Recipient:");
		for (int i = 0; i < recipients.size(); i++) {
			System.out.println(recipients.get(i));
		}
	}
	
	public static String getMyHostName(){
		String hostname = null;
		byte[] ipAddress = null;
		try {
			  InetAddress addr = InetAddress.getLocalHost();
			  ipAddress = addr.getAddress();
			  hostname = addr.getHostName();
		}catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return hostname.trim(); 
	}
	

}

